<?php

namespace app\modelservice;

use app\model\Member;

class LoginService
{

    public $userModel;

    function __construct()
    {
        $this->userModel = new Member;    
    }

    /**
     * 登录处理
     * 
     * @param array $data
     * @return string
     */
    public function login($data)
    {
        $user = $this->getUserByname($data['username']);
        if (!$user) {
            throw new \Exception('user not found');
        }
        
        $password = signPassword($data['password']);
        if ($password != $user['password']) {
            throw new \Exception('wrong password');   
        }

        return signToken($user['id']);
    }

    private function getUserByname($username)
    {
        return $this->userModel
            ->where('nickname', '=', $username)
            ->whereOr('mobile', '=', $username)
            ->whereOr('email', '=', $username)
            ->findOrEmpty();
    }
}